#!/usr/bin/env python

# # Copyright (c) 2010 Harry Delmolino

# # Permission is hereby granted, free of charge, to any person obtaining a copy
# # of this software and associated documentation files (the "Software"), to deal
# # in the Software without restriction, including without limitation the rights
# # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# # copies of the Software, and to permit persons to whom the Software is
# # furnished to do so, subject to the following conditions:

# # The above copyright notice and this permission notice shall be included in
# # all copies or substantial portions of the Software.

# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# # THE SOFTWARE.

from PyQt4 import QtCore, QtGui
import os
import urllib

class ImageViewer(QtGui.QMainWindow):
	def __init__(self):
		super(ImageViewer, self).__init__()

		self.imgList = []
		
		self.imageLabel = QtGui.QLabel()
		self.imageLabel.setAlignment(QtCore.Qt.AlignCenter)
		
		self.setCentralWidget(self.imageLabel)

		self.setWindowTitle("Image Viewer")
		self.showMaximized()
			
	def download(self, url):
		fileName = url.split('/')[-1]
		urllib.urlretrieve(url, fileName)
		return fileName
		
	def open(self, url = None):
		if os.path.isfile(url):
			return os.path.abspath(url)
		else:
			return os.path.abspath(self.download(url))

	def load(self, url = None):
		fileName = self.open(url)
		if fileName:
			image = QtGui.QImage(fileName)
			if image.isNull():
				QtGui.QMessageBox.information(self, "Image Viewer", "Cannot load %s." % fileName)
				return
			if image.size().width() > self.imageLabel.size().width() or image.size().height() > self.imageLabel.size().height():	  
				return QtGui.QPixmap.fromImage(image).scaled(self.imageLabel.size().width(), self.imageLabel.size().height(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.FastTransformation)
			else:
				return QtGui.QPixmap.fromImage(image)
				
	def nextPic(self, list = None):
		list = self.imgList
		if not list:
			QtGui.QMessageBox.information(self, "Image Viewer", "No image to load.")
			return
		self.imageLabel.setPixmap(self.load(self.imgList.pop(0)))

	def keyPressEvent(self, event):
		if type(event) == QtGui.QKeyEvent:
			if event.key() == ord('N'):
				self.nextPic()
			event.accept()
		else:
			event.ignore()

